<template>
  <div>
    <AplidForm
      ref="formRef"
      v-bind="formConfig?formConfig:BaseFormConfig"
      v-model="formModel"
      @change="handleItemChange"
      @submit="onSubmit">
    </AplidForm>
  </div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod'
import { BaseFormConfig } from '@/views/datacenter/basicData/serviceFacility/config'
import { useCommonStore } from '@/stores/common'
import { getAreaObj } from '@/utils/util'
import { ElMessageBox } from 'element-plus'
const { setTempParams } = useCommonStore()

const props = defineProps<{
  formConfig?:any
}>()

const emit = defineEmits(['refresh','gatherParams','back'])
const formModel:any = ref({})
const formRef = ref()

const onSubmit = (form, done) => {

  const areaObj: any = getAreaObj(form.areas,'')
  const areaName: any = getAreaObj(form.areas_name,'')
  // 需要将这个参数传给拓展信息
 const params = {
      ...form,
      ...areaObj,
      ...areaName,
      code:2002,
      areas: undefined,
      areas_name:undefined,
      unitNameCreditCode:undefined
  }
  if(form.dailyDeliveryOfFoodAid && Array.isArray(form.dailyDeliveryOfFoodAid)) {
    params.dailyDeliveryOfFoodAid = form.dailyDeliveryOfFoodAid.join(',')
  }
  emit('gatherParams',params)
  // 直接提交需要走这
  apiMod.dpServiceFacility_gather(params).then(res=>{
  emit('refresh', res.data)
  // 关闭加载动画
  done()
  }).catch(err=>{
    done()
  })
  // 要把三个表的关联值传入到配置项中
  setTempParams({name:form.name})
 
}
const openTip = () => {
  ElMessageBox.confirm('设施唯一值重复,是否重新输入?', '提示', {
    confirmButtonText: '退出',
    cancelButtonText: '重新输入',
    type: 'warning',
  })
    .then(() => {
      emit('back')
    })
    .catch(() => {
      formModel.value.soleValue = undefined
    })
}

const handleItemChange = (model, item, e) => {
  // 校验唯一代码是否已存在
  if (item.prop == 'soleValue') {
    if(e !==''){
       apiMod.dpServiceFacility_page({ soleValue: e }).then((res) => {
        console.log('有没有重复', res)
        const data = res.data
        if (data.records.length > 0) {
          openTip()
        }
      })
    }
  }
}
const onSave = () => {
  formRef.value!.onSubmit()
}
defineExpose({
  onSave
})
</script>

<style scoped></style>
